package cn.ibizlab.businesscentral.core.extensions.service;

import cn.ibizlab.businesscentral.core.odoo_account.domain.Account_fiscal_position;
import cn.ibizlab.businesscentral.core.odoo_account.domain.Account_tax;
import cn.ibizlab.businesscentral.core.odoo_base.domain.Res_lang;
import cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_product;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_supplier_taxes_rel;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_supplierinfo;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_template;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_order;
import cn.ibizlab.businesscentral.core.odoo_purchase.service.impl.Purchase_order_lineServiceImpl;
import cn.ibizlab.businesscentral.util.dict.StaticDict;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_order_line;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * 实体[采购订单行] 自定义服务对象
 */
@Slf4j
@Primary
@Service("Purchase_order_lineExService")
public class Purchase_order_lineExService extends Purchase_order_lineServiceImpl {

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_templateService productTemplateService;

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_base.service.IRes_langService langService;

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_supplier_taxes_relService productSupplierTaxesRelService;

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_taxService accountTaxService;

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_supplierinfoService supplierinfoService;

    @Autowired
    private cn.ibizlab.businesscentral.core.odoo_account.service.IAccount_fiscal_positionService accountFiscalPositionService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Calc_price]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_order_line calc_price(Purchase_order_line et) {

        // 单一税的计算
        BigDecimal priceUnit = new BigDecimal(et.getPriceUnit());
        BigDecimal productQty = new BigDecimal(et.getProductQty());

        // 计算price_subtotal， 小计
        BigDecimal priceSubTotal = productQty.multiply(priceUnit);
        et.setPriceSubtotal(priceSubTotal);
        JSONArray jsonArray = JSONArray.parseArray(et.getTaxesId());
        Long taxId = jsonArray.getJSONObject(0).getLong("srfkey");
        Account_tax accountTax = accountTaxService.get(taxId);
        // 计算price_tax，税率
        Double priceTax = null;
        // 固定税
        if(StringUtils.compare(accountTax.getAmountType(), StaticDict.ACCOUNT_TAX__AMOUNT_TYPE.FIXED.getValue()) == 0){
            //
            priceTax = accountTax.getAmount() * productQty.doubleValue();
        }
        // 价格中是否已经含税
        Boolean priceInclude = accountTax.getPriceInclude();
        // 价格不含税，税的类型为价格百分比
        if(StringUtils.compare(accountTax.getAmountType(), StaticDict.ACCOUNT_TAX__AMOUNT_TYPE.PERCENT.getValue()) == 0 && !priceInclude){
            priceTax = priceSubTotal.doubleValue() * accountTax.getAmount() / 100;
        }
        // 价格含税，税的类型为价格百分比
        if(StringUtils.compare(accountTax.getAmountType(), StaticDict.ACCOUNT_TAX__AMOUNT_TYPE.PERCENT.getValue()) == 0 && priceInclude){
            priceTax = priceSubTotal.doubleValue() - (priceSubTotal.doubleValue() / (1 + accountTax.getAmount() / 100));
        }
        // 价格不含税，税的类型为含税价格百分比
        if(StringUtils.compare(accountTax.getAmountType(), StaticDict.ACCOUNT_TAX__AMOUNT_TYPE.DIVISION.getValue()) == 0 && priceInclude){
            if((1-accountTax.getAmount()/100) > 0){
                priceTax = priceSubTotal.doubleValue() / (1 - accountTax.getAmount() / 100) - priceSubTotal.doubleValue();
            }else{
                priceTax = 0.0;
            }
        }
        // 价格含税，税的类型为含税价格百分比
        if(StringUtils.compare(accountTax.getAmountType(), StaticDict.ACCOUNT_TAX__AMOUNT_TYPE.DIVISION.getValue()) == 0 && priceInclude){
            priceTax = priceSubTotal.doubleValue() - (priceSubTotal.doubleValue() * (accountTax.getAmount() / 100));
        }
        et.setPriceTax(priceTax);

        // 计算price_total， 总计
        BigDecimal priceTotal = priceSubTotal.add(new BigDecimal(priceTax));
        et.setPriceTotal(priceTotal);

        return super.calc_price(et);
    }
    /**
     * 自定义行为[Product_change]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_order_line product_change(Purchase_order_line et) {
        // 判断当前的订单行的id
        if(et.getId() != null){
            // 根据product更新订单行的数据
            // 重新设置订单行的datePlanned,并将price_unit和product_qty设置为0
            et.setDatePlanned(new Timestamp(System.currentTimeMillis()));
            et.setPriceUnit(0.0);
            et.setProductQty(0.0);

            // _product_id_change()方法
            // 重新设置当前所选产品的计量单位
            Product_product product = productProductService.get(et.getProductId());
            Product_template productTemplate = productTemplateService.get(product.getProductTmplId());
            if(productTemplate.getUomPoId() != null){
                et.setProductUom(productTemplate.getUomPoId());
            }else {
                et.setProductUom(productTemplate.getUomId());
            }
            // 重新设置订单行中产品的说明内容，未处理完毕
            // name的获取
            Res_partner partner = resPartnerService.get(et.getPartnerId());
            // 语言处理
//            partner.getLang();
            String name = productTemplate.getName();
            et.setName(name);

            // 计算taxid _compute_tax_id
            Purchase_order order = purchaseOrderService.get(et.getOrderId());
            Long fpos = null;
            if (order.getFiscalPositionId() != null) {
                fpos = order.getFiscalPositionId();
            }else{
                // line.order_id.partner_id.with_context(force_company=line.company_id.id).property_account_position_id, 未处理
                List<Account_fiscal_position> accountFiscalPositions = accountFiscalPositionService.selectByCompanyId(et.getCompanyId());

            }
            // 获取当前产品的默认税种
            JSONArray jsonArray = new JSONArray();
            List<Product_supplier_taxes_rel> productSupplierTaxesRels = productSupplierTaxesRelService.selectByProdId(productTemplate.getId());
//            List<Account_tax> taxes = new ArrayList<>();
            if(productSupplierTaxesRels.size() != 0){
                for(Product_supplier_taxes_rel productSupplierTaxesRel : productSupplierTaxesRels){
                    Account_tax accountTax = accountTaxService.get(productSupplierTaxesRel.getTaxId());
                    if(accountTax.getCompanyId() != order.getCompanyId()){
                        productSupplierTaxesRels.remove(productSupplierTaxesRel);
                    }else{
//                        taxes.add(accountTax);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("srfkey", accountTax.getId());
                        jsonObject.put("srfmajortext", accountTax.getName());
                        jsonArray.add(jsonObject);
                    }
                }
            }
            if(fpos != null){
                // 调用map_tax()方法， 未处理
                et.setTaxesId("");
            }else{
                et.setTaxesId(jsonArray.toString());
            }


            // 设置订单行的产品数量 _suggest_quantity(),使用供应商的供应的最小数量和单位
            // 获取供应商的最小供应数量,需要检测
            Double minQty = 0.0;
            Long productUom = 0L;
            List<Product_supplierinfo> productSupplierinfos = supplierinfoService.selectByProductTmplId(productTemplate.getId());
            // 找到该产品最小供应数量以及计量单位
            if(productSupplierinfos.size() != 0){
                for(Product_supplierinfo supplierinfo : productSupplierinfos){
                    if(supplierinfo.getName() == order.getPartnerId() && (!(supplierinfo.getProductId()!=null) || supplierinfo.getProductId() == et.getProductId())){
                        if(supplierinfo.getMinQty() != 0){
                            if(minQty == 0.0){
                                minQty = supplierinfo.getMinQty();
                                productUom = supplierinfo.getProductUom();
                            }else if(supplierinfo.getMinQty() < minQty){
                                minQty = supplierinfo.getMinQty();
                                productUom = supplierinfo.getProductUom();
                            }
                        }
                    }
                }
            }
            if(minQty != 0.0){
                et.setProductQty(minQty);
                et.setProductUom(productUom);
            }else{
                et.setProductQty(1.0);
            }


            // _onchange_quantity(),
            Map params = new HashMap();
            params.put("order_id", et.getOrderId());
            Long seller = null;
            // 未处理，需要调用产品模块中的_select_seller()方法'

            Product_supplierinfo supplierinfo = supplierinfoService.get(seller);
            // 判断需不需要重新设置计划日期
            if(seller != null || et.getDatePlanned() == null){
                // self._get_date_planned(seller).strftime(DEFAULT_SERVER_DATETIME_FORMAT)， 未处理
                Timestamp dateOrder = order.getDateOrder();
                Long time = 0L;
                if(dateOrder != null){
                    if(seller != null){
                        time = dateOrder.getTime() + supplierinfo.getDelay() * 24 * 60 * 60;

                    }else{
                        time = dateOrder.getTime();
                    }
                }else{
                    if(seller != null){
                        time = new Date().getTime() + supplierinfo.getDelay() * 24 * 60 * 60;
                    }else{
                        time = new Date().getTime();
                    }
                }
                Timestamp datePlanned = new Timestamp(time);
                et.setDatePlanned(datePlanned);
            }

            if(seller == null){
                // 未处理
                List<Product_supplierinfo> supplierinfos = supplierinfoService.selectByProductTmplId(productTemplate.getId());
                if(supplierinfos.size() != 0){
                    for(Product_supplierinfo supplierinfo1 : supplierinfos){
                        if(supplierinfo1.getName() == et.getPartnerId()){
                            et.setPriceUnit(0.0);
                        }
                    }
                }
            }else{
                Double priceUnit = 10.0; // 模拟数据
                if(seller != null){
                    // price_unit = self.env['account.tax']._fix_tax_included_price_company(seller.price, self.product_id.supplier_taxes_id, self.taxes_id, self.company_id) , 未处理
                    // 调用account.py中的_fix_tax_included_price_company()方法,未处理
                    Double price = supplierinfo.getPrice();
                    log.warn("链接_fix_tax_included_price_company()");
                }

                if(priceUnit != 0.0 && order.getCurrencyId() != null && supplierinfo.getCurrencyId() != order.getCurrencyId()){
                    // 当当前订单的币种和供应商所用币种不同时，进行转换，获取转换后的单价, _convert方法 未处理
                    log.warn("链接_convert()");
                    priceUnit = priceUnit;
                }

                // 判断当前使用的计量单位和供应商的计量的单位是否相同，通过供应商的计量单位来重新计算单价
                if(seller != null && et.getProductUom() != null && supplierinfo.getProductUom() != et.getProductUom()){
                    // seller.product_uom._compute_price(price_unit, self.product_uom), 未处理
                    priceUnit = priceUnit;
                }
                et.setPriceUnit(priceUnit);
            }

//             计算税前和税后的总价
//            et = this.calc_price(et);
        }
        return super.product_change(et);
    }
}

